import { ref, reactive, shallowRef } from 'vue'
import * as echarts from 'echarts'
import getInitOption from '../options/PressureOption'
import { getSingleColor } from '../utils/colorUtils'

const chartInstance = shallowRef() // 图表实例
const allPressureData1 = reactive([]) // 数据
const allPressureData2 = reactive([]) // 数据
const config = ref({ max: 1, min: 0 }) // 图表配置
const titleFontSize = ref(0) // 图表字体大小
const pressureRef = shallowRef()

function registerPressure(pressure) {
  pressureRef.value = pressure
}
function initChart() {
  chartInstance.value = echarts.init(pressureRef.value, 'dark')
  chartInstance.value.setOption(getInitOption(config.value))
}
function screenAdapter() {
  titleFontSize.value = (pressureRef.value.offsetWidth / 100) * 4
  const apdaterOption = {
    title: {
      textStyle: {
        fontSize: titleFontSize.value
      }
    },
    series: [
      {
        progress: {
          width: titleFontSize.value * 2
        },
        axisLine: {
          lineStyle: {
            width: titleFontSize.value * 2
          }
        },
        axisTick: { distance: -titleFontSize.value * 2.5 },
        splitLine: {
          distance: -titleFontSize.value * 3,
          length: titleFontSize.value * 0.75
        },
        axisLabel: {
          distance: -titleFontSize.value + 5,
          fontSize: titleFontSize.value * 1.5
        },
        detail: {
          lineHeight: titleFontSize.value * 2,
          fontSize: titleFontSize.value * 2
        }
      },
      {
        progress: {
          width: titleFontSize.value * 0.75
        }
      }
    ]
  }
  chartInstance.value.setOption(apdaterOption)
  chartInstance.value.resize()
}
function updatePressure(data, status) {
  const pressureData1 = {
    value: data,
    itemStyle: {
      color: status === 1 ? getSingleColor(0) : getSingleColor(2)
    }
  }
  const pressureData2 = {
    value: data,
    itemStyle: {
      color: status === 1 ? getSingleColor(1) : getSingleColor(3)
    }
  }
  allPressureData1[0] = pressureData1
  allPressureData2[0] = pressureData2
  const dataOption = {
    series: [
      {
        data: allPressureData1
      },
      {
        data: allPressureData2
      }
    ]
  }
  chartInstance.value.setOption(dataOption)
}

export const usePressure = () => {
  return {
    registerPressure,
    initChart,
    screenAdapter,
    updatePressure
  }
}
